package com.huike.clues.service.impl;

import com.huike.clues.service.ISysFileService;
import com.huike.common.config.MinioConfig;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.utils.uuid.UUIDUtils;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
@Slf4j
public class SysFileServiceImpl implements ISysFileService {

    @Autowired
    private MinioConfig minioConfig;

    @Override
    public AjaxResult upload(MultipartFile file) {

        InputStream inputStream = null;
        //创建连接对象
        MinioClient minioClient = getClient();
        //获取桶的名字
        String bucketName = minioConfig.getBucketName();
        //判断文件存储的桶是否存在
        try {
             inputStream = file.getInputStream();
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found){
                //如果桶不存在就创建一个
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            //操作文件
            String filename  = file.getOriginalFilename();
            //合同.pdf
            //我们存到minio里的不能叫合同.pdf 为什么？怕重名
            String boject = UUIDUtils.getUUID()+".pdf";
            //文件上传
            PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(bucketName).object(boject)
                    .contentType(file.getContentType())
                    .stream(inputStream,file.getSize(),-1)
                    .build();
            minioClient.putObject(putObjectArgs);
            //封装访问的url给前端
            AjaxResult success = AjaxResult.success();
            success.put("filename","/"+bucketName+"/"+boject);
            //url需要进行截取
            success.put("url",minioConfig.getEndpoint()+":"+minioConfig.getPort()+"/"+minioConfig.getBucketName()+filename);
            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败");
        }finally {
            //防止内存泄漏
            if (inputStream != null){
                try {
                    inputStream.close();//关闭流
                } catch (IOException e) {
                    log.debug("inputStream close IOException:"+e.getMessage());
                }
            }
        }

    }

    private MinioClient getClient(){
        //创建配置类对象 , 新版 MinIO 采用 Builder构建者模式来构造 MinioClient对象。
        MinioClient minioClient = MinioClient.builder()
                .endpoint("http://"+minioConfig.getEndpoint()+":"+minioConfig.getPort())
                .credentials(minioConfig.getAccessKey(),minioConfig.getSecretKey())
                .build();
        return minioClient;
    }
}
